<template>
  <div>
    <el-card shadow="hover" class="layout-padding-auto">
      <TableSearch
        :search="state.search"
        @search="onSearch"
        @listenClick="listenClick"
      />
      <Table
        ref="tableRef"
        v-bind="state.tableData"
        class="table-demo"
        @pageChange="onTablePageChange"
        @listenClick="listenClick"
        @dataList="dataList"
      >
        <template #default="{ slotData, slotColumn }">
          <div v-if="slotColumn.key === 'planType'">
            {{ slotData.planType == 1 ? '单次维护' : '周期维护' }}
          </div>
          <div v-if="slotColumn.key === 'period'">
            <!-- {{ slotData.period + slotData.periodUnit }} -->
            {{
              slotData.period === '' || slotData.period.length === 0
                ? '-'
                : slotData.period + slotData.periodUnit
            }}
          </div>
        </template>
      </Table>
      <PlanDetail
        :planDetailDialog="planDetailDialog"
        :dialogForm="dialogForm"
        @closeDetail="closeDetail"
      ></PlanDetail>
    </el-card>
  </div>
</template>
<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive, defineAsyncComponent, onMounted } from 'vue'
import {
  batchBuildMaintainPlanApi,
  deleteMaintainPlanApi,
  deletePlanDeviceApi,
  getPlanInfoApi
} from '/@/api/maintain'
import { dictionaryList } from '/@/api/publicApi'
import routes from '/@/router'
import { getButtonListByRoleApi } from '/@/api/publicApi'
import { Session } from '/@/utils/storage'
const menu = Session.get('menu')
const buttonCodes = ref<any>([])
const Table = defineAsyncComponent(
  () => import('/@/components/table/index.vue')
)
const TableSearch = defineAsyncComponent(
  () => import('/@/components/table/search.vue')
)
const PlanDetail = defineAsyncComponent(
  () => import('./components/PlanDetail.vue')
)
// 定义变量内容
const tableRef = ref<RefType>()
const state = reactive<TableDemoState>({
  tableData: {
    flash: false, // 刷新表格
    selecta: true, // 是否有禁用项
    empty: false, // 是否清空选择
    // 表头内容（必传，注意格式）
    header: [
      {
        key: 'maintainTypeName',
        colWidth: '',
        title: '维保类型',
        type: 'text'
      },
      { key: 'planType', colWidth: '', title: '计划类型', type: 'slot' },
      {
        key: 'maintainUserName',
        colWidth: '',
        title: '维保人',
        type: 'text'
      },
      { key: 'period', colWidth: '', title: '周期', type: 'slot' },
      {
        key: 'planBeginDate',
        colWidth: '',
        title: '计划开始时间',
        type: 'text'
      },
      {
        key: 'planEndDate',
        colWidth: '',
        title: '计划结束时间',
        type: 'text'
      },
      {
        key: 'maintainDeviceNum',
        colWidth: '',
        title: '维保设备数量',
        type: 'text'
      },
      {
        key: 'maintainItemNum',
        colWidth: '',
        title: '维保项目数量',
        type: 'text'
      }
    ],
    columnBtn: [
      {
        name: 'planDetail',
        text: '详情',
        // hide(row: any): boolean {
        //   return row.status == 0
        // },
        type: 'primary',
        btns: buttonCodes.value,
        btnCode: 'wbpDetailBtn'
      },
      {
        name: 'createTask',
        text: '生成任务',
        hide(row: any): boolean {
          return false
        },
        type: 'primary',
        btns: buttonCodes.value,
        btnCode: 'wbpGenerateTasksBtn'
      },
      {
        name: 'editPlan',
        text: '编辑',
        // hide(row: any): boolean {
        //   return row.taskFlag == 0
        // },
        color: '#1962E0',
        btns: buttonCodes.value,
        btnCode: 'wbpEditBtn'
      },
      {
        name: 'delPlan',
        text: '删除',
        // hide(row: any): boolean {
        //   return row.status == 0
        // },
        type: 'danger',
        btns: buttonCodes.value,
        btnCode: 'wbpDeleteBtn'
      }
    ],
    // 配置项（必传）
    config: {
      listApi: '/device/mobile/deviceMaintainPlan/pageList',
      listHttp: 'post',
      total: 0, // 列表总数
      loading: true, // loading 加载
      noPage: false, // 是否分页
      isSerialNo: true, // 是否显示表格序号
      isSelection: true, // 是否显示表格多选
      isOperate: true, // 是否显示表格操作栏
      isExtend: true, // 是否可以扩展
      operateWidth: '350', //操作栏宽度
      fixed: 'right' //操作栏固定
    },
    // 搜索参数
    param: {},
    extendTable: {
      // 二级表格
      header: [
        { key: 'deviceNum', colWidth: '', title: '设备编号', type: 'text' },
        { key: 'deviceName', colWidth: '', title: '设备名称', type: 'text' },
        { key: 'seatNum', colWidth: '', title: '位置号', type: 'text' }
      ], // 第二级的头部
      dataProp: 'deviceInfoList', // 第二级的数据字段
      describe: true, //第二级描述
      describeProp: 'deviceItemList', //第二级描述数据字段
      describeTitle: '维保项目', //第二级描述数据字段标题
      isOperate: true, // 是否显示表格操作栏
      inx: true, // 是否显示序号
      extendBtn: [
        {
          name: 'delItem',
          text: '删除',
          // hide(row: any): boolean {
          //   return row.status == 0
          // },
          type: 'danger',
          btns: buttonCodes.value,
          btnCode: 'wbpDeleteBtn'
        }
      ]
    }
  },
  // 搜索表单，动态生成（传空数组时，将不显示搜索，注意格式）
  search: {
    param: [
      {
        label: '计划类型',
        prop: 'planType',
        placeholder: '请选择',
        options: [
          { id: '', configValue: '全部' },
          { id: 1, configValue: '单次维护' },
          { id: 2, configValue: '周期维护' }
        ],
        type: 'select'
      },
      {
        label: '维保类型',
        prop: 'maintainType',
        placeholder: '请选择',
        options: [],
        type: 'select'
      }
    ],
    btn: [
      {
        text: '新增计划',
        fun: 'addPlan',
        disable: false,
        loading: false,
        type: 'primary',
        hide(): boolean {
          return false
        },
        btns: buttonCodes.value,
        btnCode: 'wbpAddPlanBtn'
      }
      // {
      //   text: '批量生成任务',
      //   fun: 'batchCreateTask',
      //   disable: false,
      //   loading: false,
      //   type: 'primary',
      //   hide(): boolean {
      //     return true
      //   },
      //   btns: buttonCodes.value,
      //   btnCode: 'wbpBatchGenerateTasksBtn'
      // }
    ],
    reset: true
  }
})

const tableList = ref<any>([])
const dataList = (val: any) => {
  tableList.value = val.records
}

const getMaintainType = () => {
  dictionaryList({ configType: 'maintain_type', keyword: '' }).then((res) => {
    if (res.code == 0) {
      state.search.param.forEach((i: any) => {
        if (i.prop == 'maintainType') {
          i.options = res.data
          i.options.unshift({
            configValue: '全部',
            customizeFlag: 0,
            id: '',
            parentId: '0'
          })
        }
      })
    }
  })
}
getMaintainType()

// 初始化列表数据
const getTableData = () => {
  state.tableData.flash = !state.tableData.flash
}
// 搜索点击时表单回调
const onSearch = (data: EmptyObjectType) => {
  state.tableData.param = Object.assign({}, state.tableData.param, { ...data })
  // console.log(state.tableData.param);
  state.tableData.flash = !state.tableData.flash
}
// 分页改变时回调
const onTablePageChange = (page: TableDemoPageType) => {
  state.tableData.param.pageNum = page.pageNum
  state.tableData.param.pageSize = page.pageSize
  getTableData()
}

const addPlan = () => {
  routes.push({
    name: 'maintenanceAddPlan',
    query: {
      id: ''
    }
  })
}
const editPlan = (row: any) => {
  routes.push({
    name: 'maintenanceEidtPlan',
    query: {
      id: row.id
    }
  })
}

const planDetailDialog = ref(false)
const dialogForm = ref({
  title: '',
  form: ''
})
const planDetail = (row: any) => {
  getPlanInfoApi(row.id).then((res) => {
    if (res.code == 0) {
      dialogForm.value.form = res.data
      dialogForm.value.title = '计划详情'
      planDetailDialog.value = !planDetailDialog.value
    }
  })
}
const closeDetail = () => {
  planDetailDialog.value = !planDetailDialog.value
}

const createTask = (row: any) => {
  taskApi([row.id], 1)
}

const taskApi = (arr: any, type: any) => {
  ElMessageBox.confirm(
    '计划生成任务后，计划不可再次编辑，生成的任务在【维保任务】中查看，确定生成?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      batchBuildMaintainPlanApi(arr).then((res) => {
        if (res.code == 0) {
          ElMessage({
            type: 'success',
            message: '成功生成'
          })
          getTableData()
          if (type == 2) {
            state.tableData.empty = true
          }
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消'
      })
    })
}

const delPlan = (row: any) => {
  ElMessageBox.confirm(
    '<span>确定删除？</span><p></p><span>如果计划包含已发布未维保的任务也将同步删除</span>',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      dangerouslyUseHTMLString: true
    }
  )
    .then(() => {
      deleteMaintainPlanApi(row.id).then((res) => {
        if (res.code == 0) {
          ElMessage({
            type: 'success',
            message: '删除成功'
          })
          getTableData()
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消'
      })
    })
}

const delItem = (row: any) => {
  deletePlanDeviceApi(row.itemParentId, row.id).then((res) => {
    if (res.code == 0) {
      ElMessage.success('删除成功')
      getTableData()
    }
  })
}

const idArr = ref<any>([])
//批量生成
const batchCreateTask = () => {
  if (idArr.value.length == 0) {
    ElMessage.warning('请选择要生成的计划')
  } else {
    taskApi(idArr.value, 2)
    state.tableData.empty = false
  }
}

const onSelectionChange = (val: any) => {
  idArr.value = []
  val.forEach((i: any) => {
    idArr.value.push(i.id)
  })
}
const onSelect = (val: any) => {}
const onExpandChange = (val: any) => {}

const emptyBack = () => {
  state.tableData.empty = !state.tableData.empty
}

//定义方法对象 注意定义的方法 必须在上面已经申明 所以建议objFun申明和 listenClick方法 写在页面最下面
const objFun = {
  addPlan: addPlan,
  editPlan: editPlan,
  planDetail: planDetail,
  createTask: createTask,
  delPlan: delPlan,
  batchCreateTask: batchCreateTask,
  onSelectionChange: onSelectionChange,
  onSelect: onSelect,
  onExpandChange: onExpandChange,
  delItem: delItem,
  emptyBack: emptyBack
}
// 监听子级表格  传过来的方法
const listenClick = (name: string, val: any) => {
  objFun[name](val)
}

onMounted(() => {
  menu.forEach(async (element: any) => {
    if (element.menuUrl == '/maintenance/Plan') {
      let res = await getButtonListByRoleApi({
        terminalType: 1,
        menuPid: element.id
      })
      res.data.forEach((item: any) => {
        buttonCodes.value.push(item.buttonCode)
      })
    }
  })
})
</script>
<style scoped lang="scss"></style>
